<?php

class m_upload extends CI_Model{
	function __construct(){
		parent::__construct();
	}
	
	function truncate(){
		$sql = "DELETE FROM m_anggaran_tmp";
		$this->db->query($sql);
	}
	
	function create_anggaran($data){
		$this->db->insert('m_anggaran_tmp',$data);
		return $this->db->insert_id();
	}
	
	function save(){
		$sql = " INSERT INTO m_anggaran SELECT * FROM m_anggaran_tmp";
		$this->db->query($sql);
		$this->truncate();
		return 1;
	}
	
	function getlist($filter,$start,$end){
		$sql = "SELECT anggaran_id,
				CONCAT(anggaran_kd1,'.',anggaran_kd2, '.',anggaran_kd3,'.',anggaran_kd4,'.',anggaran_kd5,'.', anggaran_kd6)
				as kode,
			concat( repeat('--',anggaran_level-1),anggaran_kegiatan)as kegiatan
			,TRIM(
				CONCAT(
					IF(anggaran_vol1 IS NULL,'' ,anggaran_vol1),' ',anggaran_sat1, ' ',
					IF(anggaran_vol2 IS NULL,'' ,anggaran_vol2),' ',anggaran_sat2,' ',
					IF(anggaran_vol3 IS NULL,'' ,anggaran_vol3),' ', anggaran_sat3)
			) as satuan,
			anggaran_value,
			anggaran_value * (
				IF(anggaran_vol1 IS NULL, 1,anggaran_vol1) *
				IF(anggaran_vol2 IS NULL, 1,anggaran_vol2) *
				IF(anggaran_vol3 IS NULL, 1,anggaran_vol3) 
			) as anggaran_total
			FROM m_anggaran_tmp
			WHERE anggaran_kd1 is not null";
		$query = $this->db->query($sql);
		$total = $query->num_rows();
		
		if ($filter<>""){
				$sql .=preg_match("/WHERE/i",$sql)? " AND ":" WHERE ";
				$sql .= " (lower(anggaran_kegiatan) LIKE '%".addslashes(strtolower($filter))."%' )";
		}
		$sql .= " ORDER BY anggaran_kd1, anggaran_kd2, anggaran_kd3, anggaran_kd4, anggaran_kd5, anggaran_kd6";
		$limit = $sql." LIMIT ".$start.", ".$end;
		$query = $this->db->query($limit);
		$arr = array();
		foreach($query->result() as $q){
			$arr[] = $q; 
		}
	
		$final = array(
			'total'   => $total,
			'results' => $arr
		);
		return json_encode($final);
	}
	
}